package com.zjhb.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.zjhb.common.controller.ExcelUtil;
import com.zjhb.common.controller.ExportBean;
import com.zjhb.common.dao.BaseDao;
import com.zjhb.common.dao.Page;
import com.zjhb.common.enumutil.Area;
import com.zjhb.common.util.BeanCopy;
import com.zjhb.common.util.ResourceUtil;
import com.zjhb.common.util.ResponseUtil;
import com.zjhb.common.util.StringMyUtil;
import com.zjhb.entity.DepartmentEntity;
import com.zjhb.entity.FileEntity;
import com.zjhb.entity.PatrolEntity;

import io.jsonwebtoken.lang.Collections;
import param.KeepParam;

@RestController
@RequestMapping("/patrol")
public class PatrolController {

	@Autowired
	private BaseDao baseDao;

	@PostMapping("auto/save")
	public JSONObject autoSave(HttpServletRequest req, PatrolEntity assets) throws Exception {
		if (!ResourceUtil.isAdmin()) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		assets.setStatus("auto");
		return save(assets);
	}

	@PostMapping("time/save")
	public JSONObject timeSave(HttpServletRequest req, PatrolEntity assets) throws Exception {
		if (!ResourceUtil.isAdmin()) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		assets.setStatus("time");
		return save(assets);
	}

	@PostMapping("/save")
	public JSONObject saveAll(HttpServletRequest req, PatrolEntity assets) throws Exception {
		if (!ResourceUtil.isAdmin()) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		return save(assets);
	}

	public JSONObject save(PatrolEntity assets) throws Exception {
		JSONObject j = new JSONObject();
		if (StringMyUtil.isNotEmpty(assets.getId())) {
			PatrolEntity bean = baseDao.getById(PatrolEntity.class, assets.getId());
			BeanCopy.copyBean2Bean(bean, assets);
			baseDao.update(bean);
		} else {
			DepartmentEntity dep = baseDao.getById(DepartmentEntity.class, assets.getDepartId());
			assets.setCreateTime(ResourceUtil.getNowTime());
			assets.setDepartName(dep.getName());
			assets.setCreateUser(ResourceUtil.getCurrentUser().getId());
			baseDao.save(assets);
		}
		if (!Collections.isEmpty(assets.getWjIds())) {
			for (String wjId : assets.getWjIds()) {
				FileEntity file = baseDao.getById(FileEntity.class, wjId);
				file.setTableName(assets.getId());
				baseDao.update(file);
			}
		}
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	@PostMapping("/delete/{id}")
	public JSONObject delete(@PathVariable String id) {
		if (!ResourceUtil.isAdmin()) {
			return ResponseUtil.getMap(ResponseUtil.OTHER_CODE, "您没有该权限", "");
		}
		JSONObject j = new JSONObject();
		baseDao.delete(PatrolEntity.class, id);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", "");
		return j;
	}

	@PostMapping("time/list")
	public JSONObject timeList(HttpServletRequest req, KeepParam param, HttpServletResponse resp) throws Exception {
		param.setStatus("time");
		return list(param, resp);
	}

	@PostMapping("auto/list")
	public JSONObject autoList(HttpServletRequest req, KeepParam param, HttpServletResponse resp) throws Exception {
		param.setStatus("auto");
		return list(param, resp);
	}

	@RequestMapping("/auto/down")
	public void autodown(KeepParam param, HttpServletRequest request, HttpServletResponse resp) throws Exception {
		// 语言选择
		if (!ResourceUtil.validate(request)) {
			return;
		}
		param.setStatus("auto");
		Criteria crt = baseDao.getCriteria(PatrolEntity.class);
		if (StringMyUtil.isNotEmpty(param.getDepatmentId())) {
			crt.add(Restrictions.eq("departId", param.getDepatmentId()));
		}
		crt.add(Restrictions.eq("status", param.getStatus()));
		if (StringMyUtil.isNotEmpty(param.getAreaId())) {
			crt.add(Restrictions.eq("areaId", param.getAreaId()));
		}
		if (StringMyUtil.isNotEmpty(param.getPatrolUser())) {
			crt.add(Restrictions.like("patrolUser", param.getPatrolUser(),MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(),MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getStartDate()) && StringMyUtil.isNotEmpty(param.getEndDate())) {
			crt.add(Restrictions.between("createTime", 
					ResourceUtil.getJsonTime(param.getStartDate()),ResourceUtil.getJsonTime(param.getEndDate())));
		}
		List<PatrolEntity> list = crt.list();
		if (list.size() > 0) {
			for (PatrolEntity entity : list) {
				entity.setAreaName(Area.parse(entity.getAreaId()).getValue());
			}
		}
		ExportBean<PatrolEntity> bean = new ExportBean<>();
		bean.setPoList(list);
		bean.setHeader(new String[] { "名称", "单位名称", "区域", "责任人", "巡检人", "电话", "位置", "异常描述" });
		bean.setHeaderSize(8);
		bean.setTitle("巡检");
		resp.setHeader("Content-Disposition",
				"attachment;filename=" + new String("巡检.xls".getBytes("gb2312"), "ISO8859-1"));
		ExcelUtil.exportFromBean(bean, resp.getOutputStream());
	}

	@RequestMapping("/time/down")
	public void timedown(KeepParam param, HttpServletRequest request, HttpServletResponse resp) throws Exception {
		// 语言选择
		if (!ResourceUtil.validate(request)) {
			return;
		}
		param.setStatus("time");
		Criteria crt = baseDao.getCriteria(PatrolEntity.class);
		if (StringMyUtil.isNotEmpty(param.getDepatmentId())) {
			crt.add(Restrictions.eq("departId", param.getDepatmentId()));
		}
		crt.add(Restrictions.eq("status", param.getStatus()));
		if (StringMyUtil.isNotEmpty(param.getAreaId())) {
			crt.add(Restrictions.eq("areaId", param.getAreaId()));
		}
		if (StringMyUtil.isNotEmpty(param.getPatrolUser())) {
			crt.add(Restrictions.like("patrolUser", param.getPatrolUser(),MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(),MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getStartDate()) && StringMyUtil.isNotEmpty(param.getEndDate())) {
			crt.add(Restrictions.between("createTime", 
					ResourceUtil.getJsonTime(param.getStartDate()),ResourceUtil.getJsonTime(param.getEndDate())));
		}
		List<PatrolEntity> list = crt.list();
		if (list.size() > 0) {
			for (PatrolEntity entity : list) {
				entity.setAreaName(Area.parse(entity.getAreaId()).getValue());
			}
		}
		ExportBean<PatrolEntity> bean = new ExportBean<>();
		bean.setPoList(list);
		bean.setHeader(new String[] { "名称", "单位名称", "区域", "责任人", "巡检人", "电话", "位置", "备注" });
		bean.setHeaderSize(8);
		bean.setTitle("巡检");
		resp.setHeader("Content-Disposition",
				"attachment;filename=" + new String("巡检.xls".getBytes("gb2312"), "ISO8859-1"));
		ExcelUtil.exportFromBean(bean, resp.getOutputStream());
	}

	private JSONObject list(KeepParam param, HttpServletResponse resp) throws Exception {
		JSONObject j = new JSONObject();
		Page<PatrolEntity> page = new Page<>();
		Criteria crt = baseDao.getCriteria(PatrolEntity.class);
		if (StringMyUtil.isNotEmpty(param.getDepatmentId())) {
			crt.add(Restrictions.eq("departId", param.getDepatmentId()));
		}
		crt.add(Restrictions.eq("status", param.getStatus()));
		if (StringMyUtil.isNotEmpty(param.getAreaId())) {
			crt.add(Restrictions.eq("areaId", param.getAreaId()));
		}
		if (StringMyUtil.isNotEmpty(param.getPatrolUser())) {
			crt.add(Restrictions.like("patrolUser", param.getPatrolUser(),MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getName())) {
			crt.add(Restrictions.like("name", param.getName(),MatchMode.ANYWHERE));
		}
		if (StringMyUtil.isNotEmpty(param.getStartDate()) && StringMyUtil.isNotEmpty(param.getEndDate())) {
			crt.add(Restrictions.between("createTime", 
					ResourceUtil.getJsonTime(param.getStartDate()),ResourceUtil.getJsonTime(param.getEndDate())));
		}
		crt.setMaxResults(param.getLimit());
		crt.setFirstResult(param.getOffset());
		crt.addOrder(Order.desc("createTime"));
		List<PatrolEntity> list = crt.list();
		if (list.size() > 0) {
			for (PatrolEntity entity : list) {
				entity.setAreaName(Area.parse(entity.getAreaId()).getValue());
			}
		}
		Long totalNum = baseDao.getCount(crt);
		page.setRows(list);
		page.setTotal(totalNum);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", page);
		return j;

	}

	@PostMapping("find/{id}")
	public JSONObject find(@PathVariable String id) {
		JSONObject j = new JSONObject();
		PatrolEntity bean = baseDao.getById(PatrolEntity.class, id);
		bean.setAreaName(Area.parse(bean.getAreaId()).getValue());
		Criteria crt = baseDao.getCriteria(FileEntity.class);
		crt.add(Restrictions.eq("tableName", id));
		List<FileEntity> list = crt.list();
		bean.setFiles(list);
		j = ResponseUtil.getMap(ResponseUtil.TRUE_CODE, "", bean);
		return j;
	}

}
